<?php
declare (strict_types = 1);

namespace app\common\middleware\annotate;

use think\facade\Config;
use ReflectionClass;
use app\common\annotate\permission;
class PermissionMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {

        $url = array_values(array_filter(explode("/" , $request->request('s') ?? $request->pathinfo())));
        if($url)
        {

            $app = array_shift($url);
            $suffix  =Config::get('route.controller_suffix') ? ucfirst(Config::get('route.controller_layer')) :'';
            $controller = str_replace(".", "\\", array_shift($url) ?? 'Index') ;
            $parts = explode("\\", $controller);
            if (!empty($parts)) {
                $lastIndex = count($parts) - 1;
                $parts[$lastIndex] = ucfirst($parts[$lastIndex]);
                $controller = implode("\\", $parts);
            }
    
            $action     =   array_shift($url) ?? 'index';
            $classObject = "\\app\\{$app}\\controller\\{$controller}{$suffix}";
    
    //        halt($controllers);
    
            try {
                $class = new ReflectionClass($classObject);
                $permission = $class->getAttributes(\app\common\annotate\permission::class);
                $Ispermission = true;
                # 判断类上是否存在permission注解
                if ($permission)
                {
    
                    # 如果存在
                    $permission = $permission[0]->newInstance();
                    # 表示需要权限
                    $permissionName = $permission->value;

                    $request->permission = $Ispermission = $permissionName;
                } else {
                    # 判断方法上是否存在permission注解
                    $action = $class->getMethod($action);
                    $permission = $action->getAttributes(permission::class);
                    if ($permission)
                    {
                        # 如果存在
                        $permission = $permission[0]->newInstance();
                        # 表示需要权限
                        $permissionName =$Ispermission = $permission->value;
                        $request->permission = $permissionName;
                    }
                }
    
                $request->permission = $request->permission ?? true;
    
    
            } catch (\Exception $e)
            {
    
            }
        }
      
        return $next($request);
    }
}
